package cn.smile.interceptor.admin;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;
import cn.smile.bean.CodeMsg;
import cn.smile.entity.admin.Menu;
import cn.smile.entity.admin.User;
import cn.smile.util.MenuUtil;
import cn.smile.util.SessionUtil;
import cn.smile.util.StringUtil;

/**
 * 权限统一管理拦截器
 */
@Slf4j
@Component
public class AuthorityInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestURI = request.getRequestURI();
        log.info("进入权限控制拦截器 {}", requestURI);
        User loginedUser = SessionUtil.getLoginedUser();
        if (!Objects.isNull(loginedUser)) {
            List<Menu> authorities = loginedUser.getRole().getAuthorities();
            if (!MenuUtil.isExistUrl(requestURI, authorities)) {
                //进入这里，表示权限不存在，首先判断是否是ajax请求
                if (StringUtil.isAjax(request)) {
                    //表示是ajax请求
                    try {
                        log.info("该请求无权限，已ajax方式返回提示，url= {}", requestURI);
                        response.setCharacterEncoding("UTF-8");
                        response.getWriter().write(JSON.toJSONString(CodeMsg.ADMIN_NO_RIGHT));
                    } catch (IOException e) {
                        log.error("权限处理session异常, e", e);
                    }
                    return false;
                }
                //说明是普通请求，可直接重定向到无权限提示页面
                try {
                    log.info("该请求无权限，重定向到无权限提示页面，url= {}", requestURI);
                    response.sendRedirect("/system/no_right");
                } catch (IOException e) {
                    log.error("重定向到无权限页面异常, e:", e);
                }
                return false;
            }
            log.info("该请求符合权限要求，放行 {}", requestURI);
        }
        return true;
    }
}
